#include <iostream>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>

#include "../include/packet_base.h"

using namespace std;

#define MAXLINE 4096
#define SERVER_PORT 8002
#define SERVER_ADDR "127.0.0.1"

struct Packet2{
    unsigned short head;
    unsigned short cmd;
    char buff[MAXLINE - 4];
};


int Connect(){
    int client_fd;
    struct sockaddr_in seraddr;

    seraddr.sin_family = AF_INET;
    seraddr.sin_port = htons(SERVER_PORT);
    seraddr.sin_addr.s_addr = inet_addr(SERVER_ADDR);
 
    client_fd = socket(PF_INET,SOCK_STREAM,0);
    if (client_fd == -1){
        cout<<"create socket error!"<<endl;
        return -1;
    }
    
    if (-1 == connect(client_fd, (struct sockaddr*)&seraddr, sizeof(seraddr))){
        cout << "connect failed" << endl;
        return -1;
    }

    return client_fd;
}

void Test(){
    int client_fd = Connect();
    if(client_fd == -1){
        return;
    }

    char sendbuff[MAXLINE];
    Packet2 packet;

    memset(sendbuff, 0, sizeof(sendbuff));
    memset(packet.buff, 0, sizeof(packet.buff));

    cin >> packet.buff;
    unsigned short len = strlen(packet.buff);
    packet.head = ntohs(len);

    memcpy(sendbuff, &packet, MAXLINE);

    ssize_t ret = ::send(client_fd, sendbuff, len + 2, 0);
    if (ret <= 0){
        cout << "ret <= 0, exit send" << endl;
    }else{
        cout<< "send msg: " << " success " << ret <<endl;
    }

    sleep(5);
    ::close(client_fd);
}

void TestPacket(){
    int client_fd = Connect();
    if(client_fd == -1){
        return;
    }

    PacketBase base;
    base.Begin(100);
    base.WriteInt16(200);
    base.End();

    int len = base.GetBufferSize();
    ssize_t ret = ::send(client_fd, base.GetOriginBuffer(), len, 0);
    if (ret <= 0){
        cout << "ret <= 0, exit send" << endl;
    }else{
        cout<< "send msg: " << " success " << ret <<endl;
    }

    sleep(5);
    ::close(client_fd);
}

int main(int argc, char const *argv[])
{
    TestPacket();
    return 0;
}
